package com.example.coffeejava.Controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.coffeejava.Dto.CartDto;
import com.example.coffeejava.Dto.Result;
import com.example.coffeejava.Entity.Cart;
import com.example.coffeejava.Entity.UserHolder;
import com.example.coffeejava.Service.CartService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Resource
    private CartService cartService;
    @PostMapping("/add")
    public Result add(@RequestBody CartDto cartDto){
        LambdaQueryWrapper<Cart> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Cart::getInfoId,cartDto.getInfoId());
        Cart cart=cartService.getOne(lambdaQueryWrapper);
        if(cart !=null){
            cart.setNum(cart.getNum()+cartDto.getNum());
            cartService.updateById(cart);
            return Result.ok("成功");
        }else{
            Cart cart1= BeanUtil.copyProperties(cartDto,Cart.class);
        cart1.setNum(cartDto.getNum());
            cart1.setUserId(UserHolder.getUser().getId());
            cartService.save(cart1);
            return Result.ok("成功");
        }

    }
    @GetMapping("/list")
    public Result list(){
        return cartService.getlist();
    }
    @GetMapping("/del")
    public Result del(Long id){
        return Result.ok( cartService.removeById(id));
    }
}
